﻿using HotelManager.Common;
using HotelManager.Extensions;
using HotelManager.Models;
using HotelManager.Service;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace HotelManager.ViewModels
{
    public class AdminViewModel: NavigationViewModel
    {
        private readonly IDialogHostService dialog;
        private readonly IRegionManager regionManager;
        private readonly IRoleService roleService;
        private readonly IAdminService adminService;
        public AdminViewModel(IAdminService adminService,IDialogHostService dialog, IContainerProvider provider) : base(provider)
        {
            RoleLists = new ObservableCollection<RoleData>();
            UserDetailLists=new ObservableCollection<UserDetailData>();
            regionManager = provider.Resolve<IRegionManager>();
            this.dialog = dialog;
            roleService = provider.Resolve<IRoleService>();
            ExecuteCommand = new DelegateCommand<string>(Execute);
            SelectedCommand = new DelegateCommand<UserDetailData>(Selected);
            DelCommand = new DelegateCommand<UserDetailData>(Delete);
            ChangedCommand = new DelegateCommand<RoleData>(Change);
            this.adminService = adminService;
            SearchCommand = new DelegateCommand(Search);
            //获取role
            SelectedStatus = new RoleData();
            GetRoleDataAsync();
        }
        private void Execute(string Operater)
        {
            switch (Operater)
            {
                case "Add":
                    OpenDraw();
                    break;
                case "Save":
                    Save();
                    break;
                case "Upload":
                    Upload();
                    break;
            }
        }
        private void Upload()
        {
            OpenFileDialog openFileDialog= new OpenFileDialog();
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "All Image Files | *.jpeg;*.jpg;*.gif;*.png;";
            if ((bool)openFileDialog.ShowDialog())
            {
                string fileName=openFileDialog.FileName;
                var resultData=adminService.UploadImage(fileName);
                if (resultData.success)
                {
                    Photo = "http://localhost:8090/upload/" + resultData.data;
                    CurrentDto.photo= Photo;
                }
            }
        }
        private async void Delete(UserDetailData obj)
        {
            var dialogResult = await dialog.Question("温馨提示", $"确认删除用户：{obj.name}?");
            if (dialogResult.Result != ButtonResult.OK) return;
            var deleteResult = await adminService.DeleteAsync(new AdminDeleteData() {id=obj.id,photo=obj.photo });
            if (deleteResult.success)
            {
                var model = UserDetailLists.FirstOrDefault(o => o.id.Equals(obj.id));
                if (model != null)
                    UserDetailLists.Remove(model);
            }
        }
        private async void Selected(UserDetailData userData)
        {
            try
            {
                UpdateLoading(true);
                var memoResult = await adminService.GetFirstOrDefaultAsync(userData.loginId);
                if (memoResult is not null)
                {
                    CurrentDto =new UserDetailData() { id= memoResult.id,loginId= memoResult.loginId,loginPwd= memoResult.loginPwd,name= memoResult.name,phone= memoResult.phone,photo= "http://localhost:8090/upload/" +memoResult.photo,roleId= memoResult.roleId };
                    IsRightDrawerOpen = true;
                    Photo = CurrentDto.photo;
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                UpdateLoading(false);
            }
        }
        private async void Save()
        {
            if (string.IsNullOrWhiteSpace(CurrentDto.loginId)|| string.IsNullOrWhiteSpace(CurrentDto.loginPwd))
                return;
            UpdateLoading(true);
            try
            {
                string ImgName = CurrentDto.photo;
                FileInfo fileInfo= new FileInfo(ImgName);
                CurrentDto.photo = fileInfo.Name;
                if (CurrentDto.id > 0)
                {
                    var updateResult = adminService.Update(CurrentDto);
                    if (updateResult.success)
                    {
                        var todo = UserDetailLists.FirstOrDefault(t => t.id == CurrentDto.id);
                        if (todo != null)
                        {
                            todo.id = CurrentDto.id;
                            GetDataAsync(SelectedStatus == null ? 0 : SelectedStatus.RoleId, 0, 0);
                        }
                    }
                    IsRightDrawerOpen = false;
                }
                else
                {
                    var addResult = await adminService.AddAsync(CurrentDto);
                    if (addResult.success)
                    {
                        //RoleLists.Add(addResult.Result);
                        GetDataAsync(0,0,0);
                        IsRightDrawerOpen = false;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            finally { UpdateLoading(false); }
        }
        private void OpenDraw()
        {
            CurrentDto=new UserDetailData();
            Photo ="";
            IsRightDrawerOpen = true;
        }
        private string photo;
        public string Photo
        {
            get { return photo; }
            set { photo = value; RaisePropertyChanged(); }
        }
        private UserDetailData currentDto;

        public UserDetailData CurrentDto
        {
            get { return currentDto; }
            set { currentDto = value; RaisePropertyChanged(); }
        }
        private bool isRightDrawerOpen;

        public bool IsRightDrawerOpen
        {
            get { return isRightDrawerOpen; }
            set { isRightDrawerOpen = value; RaisePropertyChanged(); }
        }
        private void Search()
        {
            int roleId= SelectedStatus==null?0:SelectedStatus.RoleId;
            GetDataAsync(roleId,0,0);
        }
        private void Change(RoleData roleDatas)
        {
            SelectedStatus = roleDatas;
        }
        public ObservableCollection<RoleData> roleLists;
        public ObservableCollection<RoleData> RoleLists
        {
            get { return roleLists; }
            set { roleLists = value; RaisePropertyChanged(); }
        }
        public ObservableCollection<UserDetailData> userDetailLists;
        public ObservableCollection<UserDetailData> UserDetailLists
        {
            get { return userDetailLists; }
            set { userDetailLists = value; RaisePropertyChanged(); }
        }
        public RoleData selectedStatus;
        public RoleData SelectedStatus
        {
            get { return selectedStatus; }
            set
            { 
                selectedStatus = value;
                RaisePropertyChanged(); 
            }
        }
        public DelegateCommand<string> ExecuteCommand { get; private set; }
        public DelegateCommand<UserDetailData> SelectedCommand { get; private set; }
        public DelegateCommand<UserDetailData> DelCommand { get; private set; }
        public DelegateCommand<RoleData> ChangedCommand { get; private set; }
        public DelegateCommand SearchCommand { get;private set; }
        private async void GetRoleDataAsync()
        {
            var roleListResult = await roleService.GetAllAsync();
            if (roleListResult.Any())
            {
                RoleLists.Clear();
                RoleLists.Add(new RoleData() { RoleId=0,RoleName="请选择角色"});
                foreach (var item in roleListResult)
                {
                    RoleLists.Add(item);
                }
            }
            
        }
        private int selectedIndex;

        public int SelectedIndex
        {
            get { return selectedIndex; }
            set 
            { 
                selectedIndex = value;
                RaisePropertyChanged();
            }
        }
        private void GetDataAsync(int roleId,int pageIndex,int pageSize)
        {
            UpdateLoading(true);
            var userListResult =adminService.GetAll(roleId,pageIndex,pageSize);
            if (userListResult is not null&& userListResult.count>0)
            {
                UserDetailLists.Clear();
                foreach (var item in userListResult.data)
                {
                    item.photo = "http://localhost:8090/upload/" + item.photo;
                    UserDetailLists.Add(item);
                }
            }
            //SelectedIndex = 0;
            UpdateLoading(false);
        }
        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            
           
            GetDataAsync(SelectedStatus.RoleId, 0,0);
        }
    }
}
